<template>
  <base-breadcrumb :breadcrumb="!isAudit">
    <div class="about-master-container">
      <b-steps
        :current="stepVal"
        direction="vertical"
        @change.self="stepChange"
      >
        <b-step title="基本信息">
          <a-card
            v-show="activeKey[0]"
            slot="description"
            v-loading="loading"
            :bordered="false"
          >
            <a-form-model
              ref="ruleForm"
              :model="formData"
              :rules="rules"
            >
              <a-row>
                <a-col span="8">
                  <a-form-model-item label="结算来源" prop="typeId">
                    <a-select v-if="state !== 3" v-model="formData.typeId" :disabled="state === 3 || formData.id !== null"
                              @change="resetForm"
                    >
                      <a-select-option v-for="item in sourceArr" :key="item.id" :value="item.id">
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                   <BaseInput v-else
                      v-model="formData.typeName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="项目名称" prop="projectId">
                    <SelectDownProject v-model="formData.projectId" :allowClear="false"
                                       :disabled="state === 3 || formData.id !== null"
                                       @selectChange="resetForm"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="物资结算编码">
                    <BaseInput
                      v-model="formData.code"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="合同编号"
                    prop="materialContractCode"
                  >
                    <a-input-search
                      v-model="formData.materialContractCode"
                      placeholder="请选择"
                      class="requiredFormItem"
                      :disabled="state === 3 || formData.id !== null"
                      @search="openContract"
                      @click="openContract"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="合同名称">
                    <BaseInput
                      v-model="formData.materialContractName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="工程名称"
                    prop="constructionTypeId"
                  >
                    <a-select
                      v-model="formData.constructionTypeId"
                      disabled
                    >
                      <a-select-option
                        v-for="item in programmeArr"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="结算单编号"
                    prop="settleNum"
                  >
                    <BaseInput
                      v-model="formData.settleNum"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>

                <a-col span="8">
                  <a-form-model-item
                    label="本月合计（不含税）"
                    prop="materialCode"
                  >
                    <BaseInput
                      v-model="formData.sumCurrentMonthExTax"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="累计发生（不含税）">
                    <BaseInput
                      v-model="formData.sumulativeAmountWithoutTax"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="本月税金">
                    <BaseInput
                      v-model="formData.sumTax"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="累计税金">
                    <BaseInput
                      v-model="formData.sumulativeTax"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="本月合计（含税）">
                    <BaseInput
                      v-model="formData.sumCurrentMonthInTax"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="累计发生（含税）">
                    <BaseInput
                      v-model="formData.sumulativeAmountWithTax"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="开始时间"
                    prop="startDate"
                  >
                    <a-date-picker
                      v-model="formData.startDate"
                      value-format="YYYY-MM-DD"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="截止时间"
                    prop="endDate"
                  >
                    <a-date-picker
                      v-model="formData.endDate"
                      value-format="YYYY-MM-DD"
                      :disabled-date="disabledDate"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="累计收料小票"
                    prop="sumReceiptSize"
                  >
                    <BaseInput
                      v-model="formData.sumReceiptSize"
                      :disabled="state === 3"
                      :max-length="9"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="共收回收料小票"
                    prop="recycleReceiptSize"
                  >
                    <BaseInput
                      v-model="formData.recycleReceiptSize"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="供应商名称">
                    <BaseInput
                      v-model="formData.supplier"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="供应商编码">
                    <BaseInput
                      v-model="formData.supplierCode"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="我方单位">
                    <BaseInput
                      v-model="formData.ownDepartment"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="结算年月"
                    prop="settleMonth"
                  >
                    <a-month-picker
                      v-model="formData.settleMonth"
                      :disabled="state === 3"
                      @change="monthChange"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建人">
                    <BaseInput
                      v-model="formData.creatorName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建时间">
                    <BaseInput
                      v-model="formData.createTime"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                v-if="state !== 3"
                type="primary"
                @click="temporaryStorage()"
              >
                保存草稿
              </a-button>
              <a-button
                type="primary"
                @click="temporaryStorage(true)"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="物资结算明细">
          <a-card
            v-if="activeKey[1]"
            slot="description"
            :bordered="false"
          >
            <detail
              :id="formData.id"
              :state="state"
              :contract-id="formData.materialContractId"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
              <a-button
                type="primary"
                :disabled="!row"
                @click="next"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="相关附件">
          <a-card
            v-if="activeKey[2]"
            slot="description"
            :bordered="false"
          >
            <u-table
              :upload-list="addFile"
              :delete-url="fileDel"
              :is-show="state !== 3"
              :list-url="fileList"
              :business-id="formData.id"
              business-code="MM15"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
            </div>
          </a-card>
        </b-step>
      </b-steps>
      <div
        v-if="!isAudit"
        class="pub-header-btn page-btn-right-top"
      >
        <a-button
          v-if="state !== 3"
          type="primary"
          :loading="loading"
          :disabled="disabledSub"
          @click="submit"
        >
          提交
        </a-button>
        <BasePrintButton
          v-if="formData.id && state === 3"
          :before-print-fn="beforePrintFn"
          style="display: inline-block"
        />

        <a-button
          v-checkVisibleInDetail
          @click="$close"
        >
          关闭
        </a-button>
      </div>
      <contract-dialog
        ref="contractDialog"
        :other-params="{projectId:this.formData.projectId,typeId:this.formData.typeId}"
        @getContract="getContract"
      />
    </div>
      <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>
<script>
import contractDialog from '../components/contractDialog/contractDialog'
import detail from '../components/detail/detail'
import {
  materialListAdd,
  materialListEdit,
  audit,
  addFile,
  fileList,
  fileDel,
  findListByMainMaterialId, MaterialPrint
} from '@/api/material/settlement/settlement'
import { selectOption } from '@/api/material/goods/goods'
import SelectDownProject from '@/components/Select/SelectDownProject'
import moment from 'moment'

export default {
  name: 'a' + Date.now(),
  components: {
    contractDialog,
    detail,
    SelectDownProject
  },
  props: {
    isAudit: { // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.state = 3
        }
      }
    },
    stepVal(newVal, oldVal) {
      this.$set(this.activeKey, newVal, true)
    }
  },
  data() {
    return {
      beforePrintFn: async () => {
        let res = await MaterialPrint({ id: this.formData.id })
        return res.data.content
      },
      activeKey: [true, false, false, false, false, false, false],
      loading: false,
      disabledSub: false, //提交按钮
      stepVal: 0,
      state: Number(this.$route.query.state),
      isSubmit: false,
      row: this.$route.query.row,
      formData: {
        id: null,
        createTime: this.getNowTime(),
        creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
        typeId: null,
        code: '',
        materialContractCode: '',
        materialContractName: '',
        constructionTypeId: null,
        settleNum: '',
        sumCurrentMonthExTax: '',
        sumulativeAmountWithoutTax: '',
        sumTax: '',
        sumulativeTax: '',
        sumCurrentMonthInTax: '',
        sumulativeAmountWithTax: '',
        startDate: null,
        endDate: null,
        sumReceiptSize: '',
        recycleReceiptSize: '',
        supplier: '',
        supplierCode: '',
        settleMonth: null,
        usageConfirmationCode: '',
        materialContractId: '',
        projectName: '',
        projectCode: '',
        contractUser: '',
        usageConfirmationId: ''
      },
      rules: {
        typeId: { required: true, message: '结算来源不能为空', trigger: 'blur' },
        usageConfirmationCode: { required: true, message: '物资用量确认单编号不能为空', trigger: 'change' },
        materialContractCode: { required: true, message: '合同编号不能为空', trigger: 'change' },
        startDate: { required: true, message: '开始时间不能为空', trigger: 'change' },
        endDate: { required: true, message: '截止时间不能为空', trigger: 'change' },
        sumReceiptSize: { required: true, message: '累计收料小票不能为空', trigger: 'blur' },
        recycleReceiptSize: { required: true, message: '共收回收料小票不能为空', trigger: 'blur' },
        settleMonth: { required: true, message: '结算年月不能为空', trigger: 'change' },
        settleNum: { required: true, message: '结算单编号不能为空', trigger: 'blur' },
        projectId: { required: true, message: '项目名称不能为空', trigger: 'change' }
      },
      isNext: false,
      addFile: addFile(),
      fileDel: fileDel(),
      fileList: fileList(),
      programmeArr: [],
      sourceArr: [],
       //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  mounted: async function() {
    try {
      this.loading = true
      await this.getProgramme()
      await this.getSource()
      if (this.state !== 1) {
        this.formData.id = this.$route.query.id
        await this.getEditInfo()
        this.isSubmit = true
      }
      this.loading = false
    } catch (e) {
      this.loading = false
    }
    //获取通过获取流程配置值
   this.processConfig = await this.$getConfigFn('mm_settlement')
  },
  methods: {
    disabledSubHanlde(e) {
      this.disabledSub = e
    },
    disabledDate(current) {
      if (this.formData.startDate) {
        let startDate
        if (typeof this.formData.startDate === 'string') {
          startDate = moment(this.formData.startDate)
        } else {
          startDate = this.formData.startDate
        }
        return current && current < startDate.endOf('day')
      }
      return true
    },
    previous: function() {
      this.isNext = true
      this.stepVal--
      if (this.stepVal < 0) {
        this.stepVal = 0
      }
    },
    monthChange: function(tiem, timeString) {
      this.formData.settleMonth = timeString
    },
    resetForm(val) {
      this.formData.materialContractCode = ''
      this.formData.materialContractName = ''
      this.formData.constructionTypeId = ''
      this.formData.supplier = ''
      this.formData.supplierCode = ''
      this.formData.projectName = ''
      this.formData.projectCode = ''
      this.formData.usageConfirmationCode = ''
      this.formData.materialContractId = ''
      this.formData.contractUser = ''
      this.formData.usageConfirmationId = ''
    },
    openContract: function() {
      this.$refs.contractDialog.open()
    },
    getContract: function(row) {
      this.formData.materialContractCode = row.code
      this.formData.materialContractName = row.name
      this.formData.constructionTypeId = row.constructionTypeId
      this.formData.supplier = row.supplier
      this.formData.supplierCode = row.supplierCode
      this.formData.projectName = row.projectName
      this.formData.projectCode = row.supplierCode
      this.formData.usageConfirmationCode = ''
      this.formData.materialContractId = row.id
      this.formData.contractUser = row.contractUser
      this.formData.ownDepartment = row.ownDepartment
    },
    async getSource() {
      let res = await selectOption({ type: 8 })
      if (res.code === 200) {
        this.sourceArr = res.data
        this.formData.typeId = this.sourceArr[0].id
      }

      let res1 = await selectOption({ type: 19 })
      if (res1.code === 200) {
        this.formData.settleSourceId = res1.data[0].id
      }
    },
    async getProgramme() {
      let res = await selectOption({ type: 18 })
      if (res.code === 200) {
        this.programmeArr = res.data
      }
    },
    stepChange: function(val) {
      if (!this.formData.id && !this.isAudit) {
        if (val) {
          this.$message.warning('切换步骤前请先填写基本信息')
          this.stepVal = 0
        }
      } else {
        if (!this.isNext) {
          this.$set(this.activeKey, val, !this.activeKey[val])
        }
      }
      this.isNext = false
    },
    // 获取编辑回显数据
    async getEditInfo() {
      try {
        this.loading = true
        let res = await findListByMainMaterialId({ id: this.formData.id })
        if (res.code === 200) {
          res.data.typeId = res.data.typeId.toString()
          this.formData = this.$assign(this.formData, res.data)
        }
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
    submit() {
      // this.save('approve');
       this.setProcessConfig = null;
      if (this.isSubmit) {
          this.submitApprovalConfirm(this.isSubmit?this.processConfig:6, async(flag)=>{
          if(!flag) {
            this.loading = false
            return
          }
          this.loading = true
          let res = await audit({ baseId: this.formData.id, auditStatus: this.formData.auditStatus })
          if (res.code === this.SUCCESS_CODE) {
            this.$message.success('提交成功')
            //提交时，返回id
            this.businessId = this.formData.id;
            this.setProcessConfig = this.processConfig;
            // this.$router.push({ path: '/material/settlement/materials' })
          }
          this.loading = false
        })
      } else {
        this.$message.warning('提交之前请先暂存')
      }
    },
    temporaryStorage(isNext) {
      this.row = true
      if (this.state === 3) {
        this.next()
        return
      }
      if (this.sourceType === 1 && this.formData.materialContractCode === '') {
        return this.$message.warning('合同编号不能为空')
      }

      this.$refs.ruleForm.validate(async (valid, object) => {
        if (valid) {
          this.loading = true
          if (this.state === 2 || this.formData.id) {
            try {
              let res = await materialListEdit(this.formData)
              this.loading = false
              if (res.code === 200) {
                this.$message.success('暂存成功')
                this.isSubmit = true
                if (isNext) {
                  this.next()
                }
              }
            } catch (e) {
              this.loading = false
            }
          } else {
            try {
              let res = await materialListAdd(this.formData)
              this.loading = false
              if (res.code === 200) {
                this.formData.id = res.data.id
                this.$message.success('暂存成功')
                this.isSubmit = true
                this.getEditInfo()
                if (isNext) {
                  this.next()
                }
              }
            } catch (e) {
              this.loading = false
            }
          }
        } else {
          this.$message.warning("请填写完所有必填项信息")
          return false
        }
      })
    },
    next: function(val) {
      this.isNext = true
      this.stepVal++
    }
  }
}
</script>
